package com.example.shengyin.controller;


import com.example.shengyin.entity.Admin;
import com.example.shengyin.service.AdminService;
import com.example.shengyin.util.ImageCompressor;
import com.example.shengyin.util.ImgCom;
import com.example.shengyin.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ClassUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
public class MainController {
    @Autowired
    private AdminService service;
    @Value("${upload-path}")
    private String path;
    @Value("${upload-qianzhui}")
    private String qianzhui;
    @Value("${upload-type}")
    private int type;

    @GetMapping("/getCode")
    public Object genCode(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        response.reset();
        response.setContentType( "image/jpeg" );
        //图像数据缓冲区
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        //绘制图片
        Graphics g = bi.getGraphics();
        //获取颜色
        Color c = new Color(200, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        //生成随机数
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("code", sb.toString());
        //输出图片
        //前3个，设置不缓存
        response.setHeader( "Prama", "no-cache");
        response.setHeader( "Cache-Control", "no-cache" );
        response.setDateHeader( "Expires", 0);
        //设置内容类型
        return ImageIO.write(bi, "JPG", response.getOutputStream());
    }

    @PostMapping("upload.do")
    public Result upload(@RequestParam(name="edit") MultipartFile file){
        Map<String,Object> m=new HashMap<>();
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        System.out.println("????>>>??????"+file);
        if (file!=null &&!file.isEmpty()) {
            File f = new File(path);
            if (!f.exists())
                f.mkdirs();
            //原来的文件名
            String filename = file.getOriginalFilename();
            String houzhui = filename.substring(filename.lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;

            try {
                file.transferTo(new File(f, newName));
                m.put("code",0);
             //   String yasuo = ImageCompressor.yasuo(path,newName, filename.substring(filename.lastIndexOf('.') + 1));
              //  String yasuo = ImgCom.yasuo(path,newName, filename.substring(filename.lastIndexOf('.') + 1));
                return Result.success(newName,"添加成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        m.put("code",415);
        m.put("msg","图片没有选择");
        return Result.error(415,"图片没有选择");
    }

    @PostMapping("upload2")
    public Result upload2(@RequestParam(name="edit") MultipartFile file){
        Map<String,Object> m=new HashMap<>();
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        System.out.println("????>>>??????"+file);
        if (file!=null &&!file.isEmpty()) {
            File f = new File(path);
            if (!f.exists())
                f.mkdirs();
            //原来的文件名
            String filename = file.getOriginalFilename();
            String houzhui = filename.substring(filename.lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;

            try {
                file.transferTo(new File(f, newName));
                m.put("code",0);
              //  String yasuo = ImageCompressor.yasuo(path,newName, filename.substring(filename.lastIndexOf('.') + 1));
               // String yasuo = ImgCom.yasuo(path,newName, filename.substring(filename.lastIndexOf('.') + 1));
                return Result.success("img/"+newName,"添加成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        m.put("code",415);
        m.put("msg","图片没有选择");
        return Result.error(415,"图片没有选择");
    }
}





